package cn.mulanbay.job.web.common;

import cn.mulanbay.api.system.bean.RemoteSystemLog;
import cn.mulanbay.api.system.service.RemoteLogService;
import cn.mulanbay.business.handler.ThreadPoolHandler;
import cn.mulanbay.web.common.ApiExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.ControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * 异常处理类
 *
 * @author fenghong
 */
@ControllerAdvice
public class JobExceptionHandler extends ApiExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(JobExceptionHandler.class);

    @Lazy
    @Autowired
    RemoteLogService remoteLogService;

    @Autowired
    ThreadPoolHandler threadPoolHandler;

    @Override
    protected void addSystemLog(HttpServletRequest request, Class exceptionClass, String title, String msg, int errorCode) {
        try {
            logger.error("异常exceptionClass="+exceptionClass);
            LocalDateTime date = LocalDateTime.now();
            threadPoolHandler.pushThread(() -> {
                RemoteSystemLog log = new RemoteSystemLog();
                log.setErrorCode(errorCode);
                log.setTitle(title);
                log.setContent(msg);
                log.setOccurTime(date);
                log.setUrlAddress(request.getServletPath());
                log.setExceptionClassName(exceptionClass.getName());
                remoteLogService.addSystemLog(log);
            });
        } catch (Exception e) {
            logger.error("添加系统日志异常", e);
        }
    }

}
